import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;  // for InvocationTargetException

public class Test extends JApplet {
	private JProgressBar pb = new JProgressBar();

	public void init() {
		Container contentPane = getContentPane();
		final JButton startButton = new JButton("start");

		contentPane.setLayout(new FlowLayout());
		contentPane.add(startButton);
		contentPane.add(pb);

		startButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GetInfoThread t = new GetInfoThread(Test.this);
				t.start();

				// this is okay because actionPerformed
				// is called on the event dispatch thread
				startButton.setEnabled(false);
			}
		});
	}
	public JProgressBar getProgressBar() {
		return pb;
	}
}
class GetInfoThread extends Thread {
	Runnable getValue, setValue;
	int value, currentValue;

	public GetInfoThread(final Test applet) {
		getValue = new Runnable() {
			public void run() {
				JProgressBar pb = applet.getProgressBar();
				currentValue = pb.getValue();
			}
		};
		setValue = new Runnable() {
			public void run() {
				JProgressBar pb = applet.getProgressBar();
				pb.setValue(value);
			}
		};
	}
	public void run() {
		while(true) {
			try {
				Thread.currentThread().sleep(500);

				// This is okay because the getValue's run()
				// is invoked on the event dispatch thread
				value = (int)(Math.random() * 100);

				try {
					SwingUtilities.invokeAndWait(getValue);
				}
				catch(InvocationTargetException ite) {
					ite.printStackTrace();
				}
				catch(InterruptedException ie) {
					ie.printStackTrace();
				}

				if(currentValue != value) {
					SwingUtilities.invokeLater(setValue);
				}
			}
			catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
